package com.legendframework.core.ioc.impl;

import com.legendframework.core.Store;
import com.legendframework.core.aop.AbstractProxy;
import com.legendframework.core.ioc.BeanInstanceSuccessHandle;
import com.legendframework.core.ioc.CommonBeansGenerate;
import com.legendframework.core.ioc.annotation.Component;
import com.legendframework.core.AbstractLegendPlugin;
import com.legendframework.core.support.lang3.StringUtils;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

/**
 * @see com.legendframework.core.ioc.annotation.Component 方式的Bean注入类型
 */
public class ComponentBeansGenerate extends CommonBeansGenerate {

    private final Set<BeanInstanceSuccessHandle> beanInstanceSuccessHandles = new HashSet<>();

    public ComponentBeansGenerate(Store store) {
        super(store);
    }

    public void addSuccessHandle(BeanInstanceSuccessHandle successHandle){
        if (successHandle != null) {
            beanInstanceSuccessHandles.add(successHandle);
        }
    }

    @Override
    public String getBeanName(Class<?> cls) {
        return StringUtils.isEmpty(cls.getAnnotation(Component.class).value()) ? cls.getName() : cls.getAnnotation(Component.class).value();
    }

    @Override
    public Class<? extends Annotation> getAnnotation() {
        return Component.class;
    }

    @Override
    public void successHandle(String beanName, Object bean , AbstractLegendPlugin plugin) {
        beanInstanceSuccessHandles.forEach(item -> item.successHandle(beanName,bean,plugin));
    }

    @Override
    protected AbstractProxy getProxyAop() {
        return store.getTransactionProxy().addTransaction(store.getYamlTransaction()).addTransaction(store.getJdbcTransaction());
    }
}
